import React, { useEffect, memo, useRef, useState } from 'react';
import _ from 'lodash';
import { RouteContext } from '@ant-design/pro-layout';
import DebounceWrapper from '@/components/DebounceWrapper';
import { Button, Dropdown, Menu, Popconfirm } from 'antd';
import { MoreOutlined, LoadingOutlined } from '@ant-design/icons';
import styles from './tableHeaderButtons.less';

const HeaderButtons = DebounceWrapper(
  ({ isMobile, collapsed, menuRender, buttonList, onClick }) => {
    const containerRef = useRef(null);
    const [buttonWidthList, setButtonWidthList] = useState([]);
    const [visibleLength, setVisibleLength] = useState(buttonList.length);
    const hasDropdown = visibleLength < buttonList.length;

    // 计算可见数
    const adaptVisibleLength = () => {
      if (containerRef.current) {
        let widthList;
        const currentContentWidth = containerRef.current.parentNode.offsetWidth;
        setButtonWidthList((currentList) => {
          if (!currentList.length) {
            const childrenList = containerRef.current.childNodes;
            const childrenWidth = _.map(
              childrenList,
              (childNode) => childNode.offsetWidth + 8 + (childNode.childNodes.length > 1 ? 0 : 16),
            );
            widthList = [...childrenWidth];
            return childrenWidth;
          }
          widthList = [...currentList];
          return currentList;
        });
        if (widthList && currentContentWidth > 0) {
          let total = 0;
          for (let i = 0; i < widthList.length; i++) {
            if (_.max([total + widthList[i], total + 84]) > currentContentWidth) {
              setVisibleLength(_.max([i - 1, 0]));
              return;
            }
            total += widthList[i];
          }
        }
      }
      setVisibleLength(buttonList.length);
    };
    const adaptVisibleLengthThrottle = _.throttle(adaptVisibleLength, 500);

    // 初始化
    useEffect(() => {
      window.addEventListener('resize', adaptVisibleLengthThrottle);
      return () => {
        window.removeEventListener('resize', adaptVisibleLengthThrottle, false);
      };
    }, []);
    useEffect(() => {
      setTimeout(() => {
        adaptVisibleLengthThrottle();
      }, 300);
    }, [isMobile, collapsed, menuRender]);

    return (
      <div
        className={styles.buttonListContainer}
        style={{ opacity: _.isEmpty(buttonWidthList) ? 0 : 1 }}
      >
        <div ref={containerRef} className={styles.buttonListContent}>
          {buttonList
            .slice(0, visibleLength)
            .map(({ key, label, confirmText, loading, disabled, ...restProps }) =>
              confirmText ? (
                <Popconfirm
                  key={key}
                  okText="确定"
                  cancelText="取消"
                  title={confirmText}
                  placement="topRight"
                  disabled={!!disabled}
                  onConfirm={(e) => onClick && onClick({ event: e, key })}
                >
                  <Button loading={!!loading} disabled={!!disabled} {...restProps}>
                    {label}
                  </Button>
                </Popconfirm>
              ) : (
                <Button
                  key={key}
                  loading={!!loading}
                  disabled={!!disabled}
                  {...restProps}
                  onClick={(e) => onClick && onClick({ event: e, key })}
                >
                  {label}
                </Button>
              ),
            )}
          {hasDropdown && (
            <Dropdown
              overlay={
                <Menu
                  onClick={({ key, domEvent }) => onClick && onClick({ event: domEvent, key })}
                  items={_.map(
                    _.slice(buttonList, visibleLength),
                    ({ key, label, danger, loading, disabled }) => ({
                      key,
                      label: (
                        <>
                          {!!loading && <LoadingOutlined />}
                          {label}
                        </>
                      ),
                      danger: !!danger,
                      disabled: !!loading || !!disabled,
                    }),
                  )}
                />
              }
            >
              <Button type="primary">
                {isMobile ? null : '更多'}
                <MoreOutlined />
              </Button>
            </Dropdown>
          )}
        </div>
      </div>
    );
  },
);

const TableHeaderButtons = memo(
  HeaderButtons,
  (prevProps, nextProps) =>
    prevProps.isMobile === nextProps.isMobile &&
    prevProps.collapsed === nextProps.collapsed &&
    prevProps.menuRender === nextProps.menuRender &&
    prevProps.buttonList === nextProps.buttonList,
);

export default (props) => (
  <RouteContext.Consumer>
    {(partial) => {
      const { layout, collapsed, menuRender, isMobile } = partial || {};
      return (
        <TableHeaderButtons
          {...props}
          isMobile={isMobile}
          collapsed={collapsed}
          menuRender={layout === 'top' ? false : !!menuRender}
        />
      );
    }}
  </RouteContext.Consumer>
);
